package com.android.demo;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.demo.interpolator.LocManager;
import com.android.demo.interpolator.LocManager.Result;

public class TestLocation extends Activity {
	private static final String TAG = "TestLocation";
	public LinearLayout mLinearLayout;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Toast.makeText(this, "定位中", 0).show();
		mLinearLayout = new LinearLayout(this);
		mLinearLayout.setOrientation(LinearLayout.VERTICAL);
		
		this.setContentView(mLinearLayout);
		getLocationCell();
		
		mLinearLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				startForMap();
			}
		});
	}
	
	private void startForMap(){
		Intent i = new Intent( 
		        Intent.ACTION_PICK, 
		        Uri.parse("http://ditu.google.cn/maps?hl=zh&mrt=loc&q=31.249351,121.45905")); 
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
		        & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 

		i.setClassName("com.google.android.apps.maps","com.google.android.maps.MapsActivity"); 
		startActivityForResult(i, 10024);
	}
	
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		Log.i(TAG, "onActivityResult"+requestCode+":"+resultCode);
	}

	private void getLocationCell(){
		new Thread(){
			public void run() {
				LocManager locmanager = new LocManager();
				// key ! get location
				LocManager.Result result = locmanager.getLocationByCellidWithGoogleApi(TestLocation.this);
				mCellResult = result;
				Message msg = new Message();
				msg.obj = result;
				msg.what = 0;
				mHandler.sendMessage(msg);
			}
		}.start();
	}
	
	private void getLocationGpsOrWifiOrCellid(){
		new Thread(){
			public void run() {
				LocManager locmanager = new LocManager();
				// key ! get location
				LocManager.Result result = locmanager.getLocationByGpsOrNet(TestLocation.this);
				mGpsWifiCellResult = result;
				Message msg = new Message();
//				result.latitude = 31.249351;
//				result.longitude= 121.45905;
//				result.latitude = 26.095349;
//				result.longitude= 119.310493;
				msg.obj = result;
				msg.what = 1;
				mHandler.sendMessage(msg);
			}
		}.start();
	}
	
	private Result mCellResult;
	private Result mGpsWifiCellResult;
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if (msg.obj!=null) {
				if (msg.what == 1) {
					Toast.makeText(TestLocation.this, "gps/wifi/基站定位完成", 0).show();
					double distance = LocManager.getDistance(mCellResult.latitude, mCellResult.longitude, mGpsWifiCellResult.latitude, mGpsWifiCellResult.longitude);
					Toast.makeText(TestLocation.this, "distance = " + distance, 0).show();
				}
				else {
					Toast.makeText(TestLocation.this, "基站 定位完成 ! 开始 gps/wifi/基站定位", 0).show();
					getLocationGpsOrWifiOrCellid();
				}
				
			} else {
				Toast.makeText(TestLocation.this, "定位失败", 0).show();
				return;
			}
			
			LocManager.Result result = (LocManager.Result)msg.obj;
			addTextView("访问标记:"+result.accessToken);
			addTextView("城市:"+result.city);
			addTextView("国家:"+result.country);
			addTextView("国家代码:"+result.countryCode);
			addTextView("县:"+result.county);
			addTextView("邮政编码:"+result.postalCode);
			addTextView("区域:"+result.region);
			addTextView("街道:"+result.street);
			addTextView("街道号码:"+result.streetNumber);
			addTextView("经度:"+result.longitude);
			addTextView("纬度:"+result.latitude);
			addTextView("精确性:"+result.accuracy);
			addTextView("-------------------------");
		};
	};
	
	private void addTextView(String txt){
		TextView tv = new TextView(this);
		tv.setText(txt);
		mLinearLayout.addView(tv);
	}
}
//	// Start listener to find current location
//  LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//  String provider = locationManager.getBestProvider(new Criteria(), true);
//  
//  if (provider != null) {
//      mLastFix = locationManager.getLastKnownLocation(provider);
//      if (mLastFix != null && savedInstanceState == null) {
//          startGeocode(mLastFix);
//      }
//  }
//
//  if (mLastFix == null) {
//  }

//	private void startGeocode(Location location) {
//        new GeocoderTask(this).execute(new GeocodeQuery(location));
//    }
//	
//	private  class GeocoderTask extends AsyncTask<GeocodeQuery, Void, GeocodeQuery> {
//        private Geocoder mGeocoder;
//
//        private GeocoderTask(Context context) {
//            mGeocoder = new Geocoder(context);
//        }
//
//        protected void onPreExecute() {
//            // Show progress spinner and disable buttons
//            setProgressBarIndeterminateVisibility(true);
////            setActionEnabled(false);
//        }
//
//        protected GeocodeQuery doInBackground(GeocodeQuery... args) {
//            GeocodeQuery query = args[0];
//            GeocodeQuery result = null;
//
//            try {
//                if (!TextUtils.isEmpty(query.name)) {
//                    // Forward geocode using query
//                    List<Address> results = mGeocoder.getFromLocationName(query.name, 1);
//                    if (results.size() > 0) {
//                        result = new GeocodeQuery(results.get(0));
//                    }
//                } else if (!Double.isNaN(query.lat) && !Double.isNaN(query.lon)) {
//                    // Reverse geocode using location
//                    List<Address> results = mGeocoder.getFromLocation(query.lat, query.lon, 1);
//                    if (results.size() > 0) {
//                        result = new GeocodeQuery(results.get(0));
//                        result.lat = query.lat;
//                        result.lon = query.lon;
//                    } else {
//                        result = query;
//                    }
//                }
//            } catch (IOException e) {
////                Log.e(TAG, "Problem using geocoder", e);
//            }
//
//            return result;
//        }
//
//        protected void onPostExecute(GeocodeQuery found) {
//            setProgressBarIndeterminateVisibility(false);
//
//            // Update GUI with resolved string
////            if (found == null) {
////                mLat = Double.NaN;
////                mLon = Double.NaN;
////                mCountryCode = null;
////                setActionEnabled(false);
////            } else {
////                mTitle.setText(found.name);
////                mLat = found.lat;
////                mLon = found.lon;
////                mCountryCode = found.countryCode;
////                setActionEnabled(true);
////            }
//        }
//    }
//
//    /**
//     * Temporary object to hold geocoding query and/or results.
//     */
//    private static class GeocodeQuery {
//        String name = null;
//
//        double lat = Double.NaN;
//        double lon = Double.NaN;
////        String countryCode = WebserviceHelper.COUNTRY_US;
//
//        public GeocodeQuery(String query) {
//            name = query;
//        }
//
//        public GeocodeQuery(Location location) {
//            lat = location.getLatitude();
//            lon = location.getLongitude();
//        }
//
//        /**
//         * Summarize details of the given {@link Address}, walking down a
//         * prioritized list of names until valid text is found to describe it.
//         */
//        public GeocodeQuery(Address address) {
//            name = address.getLocality();
//            if (name == null) {
//                name = address.getFeatureName();
//            }
//            if (name == null) {
//                name = address.getAdminArea();
//            }
//            if (name == null) {
//                name = address.getPostalCode();
//            }
//            if (name == null) {
//                name = address.getCountryName();
//            }
//
//            // Fill in coordinates, if given
//            if (address.hasLatitude() && address.hasLongitude()) {
//                lat = address.getLatitude();
//                lon = address.getLongitude();
//            }
//            
////            countryCode = address.getCountryCode();
//        }
//    }